package org.carl.base.driving.service.send.impl;

import com.pugwoo.dbhelper.DBHelper;
import com.pugwoo.dbhelper.impl.SpringJdbcDBHelper;
import lombok.extern.slf4j.Slf4j;
import org.carl.base.driving.DriveManage;
import org.carl.base.driving.entity.SendMessage;
import org.carl.base.driving.service.send.SendMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@ConditionalOnBean(value ={DriveManage.class})
public class SendMessageServiceImpl implements SendMessageService {

    @Autowired
    private DBHelper dbHelper;

    public int insert(SendMessage sendMessage) {
        sendMessage.setVersion(0);
        int total = dbHelper.insert(sendMessage);
        if (total <= 0) {
            throw new RuntimeException("消息持久化失败");
        }
        return total;
    }

    public void update(SendMessage sendMessage) {
        dbHelper.update(sendMessage);
    }

    public void deleteById(String sendId) {
        dbHelper.deleteByKey(sendId);
    }

    public SendMessage selectById(String sendId) {
        if (StringUtils.isEmpty(sendId)) {
            return null;
        }
        return dbHelper.getByKey(SendMessage.class, sendId);
    }

    public void updateMessageState(String sendId, Integer messageState) {
        if (StringUtils.isEmpty(sendId) || messageState == null) {
            throw new RuntimeException("参数错误");
        }
        SendMessage sendMessageUpdate = new SendMessage();
        sendMessageUpdate.setSendId(sendId);
        sendMessageUpdate.setHandleState(messageState);
        sendMessageUpdate.setGmtConfirm(new Date());

        update(sendMessageUpdate);
    }

    public List<SendMessage> findOverdueOrder(List<Integer> stateList, String endGmtCreate) {
        if (CollectionUtils.isEmpty(stateList) || StringUtils.isEmpty(endGmtCreate)) {
            return Collections.emptyList();
        }
        return dbHelper.getAll(SendMessage.class, "and handle_state in (?) and gmt_create <= ? ", stateList, endGmtCreate);
    }
}
